"""
配置管理模块
"""

import os
from typing import Optional
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

def _get_bool_env(name: str, default: str = "false") -> bool:
    return os.getenv(name, default).strip().lower() in ("1", "true", "yes", "y", "on")

class Config:
    """配置类"""
    
    # OpenAI API配置
    OPENAI_BASE_URL: str = os.getenv("OPENAI_BASE_URL", "https://api.openai.com")
    OPENAI_API_KEY: Optional[str] = os.getenv("OPENAI_API_KEY")
    
    # 服务器配置
    HOST: str = os.getenv("HOST", "0.0.0.0")
    PORT: int = int(os.getenv("PORT", "8000"))
    
    # 日志配置
    LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
    LOG_FILE: str = os.getenv("LOG_FILE", "logs/openai_proxy.log")
    LOG_ROTATION: str = os.getenv("LOG_ROTATION", "100 MB")
    LOG_RETENTION: str = os.getenv("LOG_RETENTION", "30 days")
    LOG_FILE_ENCODING: str = os.getenv("LOG_FILE_ENCODING", "utf-8")
    # 目录配置
    LOGS_DIR: str = os.getenv("LOGS_DIR", "logs")
    REQUEST_LOGS_DIR: str = os.getenv("REQUEST_LOGS_DIR", os.path.join(LOGS_DIR, "requests"))
    
    # 请求配置
    REQUEST_TIMEOUT: int = int(os.getenv("REQUEST_TIMEOUT", "60"))
    MAX_LOG_FILES: int = int(os.getenv("MAX_LOG_FILES", "50"))
    MAX_REQUEST_BODY_BYTES: int = int(os.getenv("MAX_REQUEST_BODY_BYTES", "2097152"))  # 2MB
    
    # 请求日志存储策略
    REQUEST_LOG_RETENTION_DAYS: int = int(os.getenv("REQUEST_LOG_RETENTION_DAYS", "30"))
    REQUEST_LOG_MAX_FILES: int = int(os.getenv("REQUEST_LOG_MAX_FILES", "2000"))  # 约1000次请求的请求+响应
    
    # 访问控制
    PROXY_AUTH_TOKEN: Optional[str] = os.getenv("PROXY_AUTH_TOKEN")
    
    # 鉴权策略
    OVERRIDE_AUTHORIZATION: bool = _get_bool_env("OVERRIDE_AUTHORIZATION", "false")
    
    # 日志策略
    LOG_REQUEST_BODIES: bool = _get_bool_env("LOG_REQUEST_BODIES", "true")
    LOG_RESPONSE_BODIES: bool = _get_bool_env("LOG_RESPONSE_BODIES", "true")
    LOG_STREAM_CONTENT: bool = _get_bool_env("LOG_STREAM_CONTENT", "false")
    MAX_STREAM_LOG_BYTES: int = int(os.getenv("MAX_STREAM_LOG_BYTES", "1048576"))  # 1MB
    MAX_BODY_LOG_CHARS: int = int(os.getenv("MAX_BODY_LOG_CHARS", "4000"))
    
    # 运行模式
    DEBUG: bool = _get_bool_env("DEBUG", "false")

    # 限流配置（简单进程内）
    RATE_LIMIT_REQUESTS: int = int(os.getenv("RATE_LIMIT_REQUESTS", "60"))
    RATE_LIMIT_WINDOW_SECONDS: int = int(os.getenv("RATE_LIMIT_WINDOW_SECONDS", "60"))

    # CORS 配置
    CORS_ENABLED: bool = _get_bool_env("CORS_ENABLED", "false")
    CORS_ALLOW_ORIGINS: str = os.getenv("CORS_ALLOW_ORIGINS", "*")  # 逗号分隔或"*"
    CORS_ALLOW_CREDENTIALS: bool = _get_bool_env("CORS_ALLOW_CREDENTIALS", "false")
    CORS_ALLOW_METHODS: str = os.getenv("CORS_ALLOW_METHODS", "*")
    CORS_ALLOW_HEADERS: str = os.getenv("CORS_ALLOW_HEADERS", "*")

    # 指标配置
    METRICS_ENABLED: bool = _get_bool_env("METRICS_ENABLED", "false")
    METRICS_AUTH_REQUIRED: bool = _get_bool_env("METRICS_AUTH_REQUIRED", "false")
    
    @classmethod
    def validate(cls) -> bool:
        """验证配置"""
        if not cls.OPENAI_API_KEY:
            print("警告: 未设置OPENAI_API_KEY环境变量")
            return False
        return True
    
    @classmethod
    def print_config(cls):
        """打印配置信息"""
        print("=" * 50)
        print("OpenAI API代理服务器配置")
        print("=" * 50)
        print(f"OpenAI Base URL: {cls.OPENAI_BASE_URL}")
        print(f"OpenAI API Key: {'已设置' if cls.OPENAI_API_KEY else '未设置'}")
        print(f"服务器地址: {cls.HOST}:{cls.PORT}")
        print(f"日志级别: {cls.LOG_LEVEL}")
        print(f"请求超时: {cls.REQUEST_TIMEOUT}秒")
        print(f"日志目录: {cls.LOGS_DIR}")
        print(f"请求日志目录: {cls.REQUEST_LOGS_DIR}")
        print(f"访问令牌启用: {'是' if cls.PROXY_AUTH_TOKEN else '否'}")
        print(f"请求体大小限制: {cls.MAX_REQUEST_BODY_BYTES} bytes")
        print(f"限流: 每{cls.RATE_LIMIT_WINDOW_SECONDS}s {cls.RATE_LIMIT_REQUESTS} 次")
        print(f"请求日志保留: {cls.REQUEST_LOG_RETENTION_DAYS} 天 或最多 {cls.REQUEST_LOG_MAX_FILES} 个文件")
        print(f"CORS启用: {'是' if cls.CORS_ENABLED else '否'}")
        print(f"指标启用: {'是' if cls.METRICS_ENABLED else '否'}（鉴权: {'是' if cls.METRICS_AUTH_REQUIRED else '否'}）")
        print(f"DEBUG模式: {'是' if cls.DEBUG else '否'}")
        print("=" * 50) 